﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;
using Models;

namespace Web.Areas.Mobile.Lib
{
    public class MobileAccount : wx_usersLogic
    {
        private static string domain = System.Configuration.ConfigurationManager.AppSettings["SiteDomain"];
        private static string Prefix = "CurrentUser-" + domain;

        /// <summary>
        /// 服务号openid
        /// </summary>
        public static string OpenID
        {
            get
            {
                var day = DateTime.Now.ToString("yyMMdd");
                var keyId = Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "AccountKey" + day);
                var ak = HttpContext.Current.Request.Cookies[keyId];

                if (ak == null) return null;
                return ak.Value;
            }
        }

        private void SetOpenID(string openid)
        {
            var day = DateTime.Now.ToString("yyMMdd");
            var keyId = Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "AccountKey" + day);

            HttpCookie cookie = new HttpCookie(keyId);
            cookie.Value = openid;
            cookie.Expires = DateTime.Now.AddDays(1);
            cookie.HttpOnly = true;
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        private static string sessionKey = Prefix + "Wechat";

        public static int ID
        {
            get
            {
                try
                {
                    var day = DateTime.Now.ToString("yyMMdd");
                    var key_id = Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "ID" + day);
                    var key_key = Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "Key" + day);
                    var sessionIdValue = HttpContext.Current.Session[key_id];

                    if (sessionIdValue == null)
                    {
                        var cid = HttpContext.Current.Request.Cookies[key_id];
                        var ckey = HttpContext.Current.Request.Cookies[key_key];
                        if (cid != null && ckey != null && !string.IsNullOrWhiteSpace(cid.Value) && !string.IsNullOrWhiteSpace(ckey.Value))
                        {
                            var accountid = int.Parse(cid.Value);

                            if (ckey.Value == Common.EncryptionHelper.MD5Helper.Encryt(Prefix + accountid))
                            {
                                HttpContext.Current.Session[key_id] = accountid;

                                var user = new wx_usersLogic().Getwx_users(new wx_users { id = accountid });
                                HttpContext.Current.Session[sessionKey] = new wx_users { id = accountid, type = user.type, nickname = user.nickname, headimgurl = user.headimgurl, mobile = user.mobile };
                                HttpContext.Current.Session.Timeout = 2;

                                return accountid;
                            }
                            return 0;
                        }
                        return 0;
                    }

                    int sid;
                    int.TryParse(sessionIdValue.ToString(), out sid);
                    return sid;
                }
                catch (Exception)
                {
                    return 0;
                }

            }
        }

        public static wx_users GetUser
        {
            get
            {
                if (ID > 0)
                {
                    var user = new wx_usersLogic().Getwx_users(new wx_users { id = ID });
                    HttpContext.Current.Session[sessionKey] = new wx_users { id = ID, type = user.type, nickname = user.nickname, headimgurl = user.headimgurl, mobile = user.mobile };
                    return user;
                }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 注销
        /// </summary>
        public static void LogOut()
        {
            var now = DateTime.Now;
            var day = now.ToString("yyMMdd");
            //清除Cookie
            HttpCookie cookie = new HttpCookie(Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "ID" + day));
            cookie.Expires = now.AddSeconds(-1);
            cookie.HttpOnly = true;
            HttpContext.Current.Response.AppendCookie(cookie);

            //清除Cookie
            HttpCookie cookiekey = new HttpCookie(Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "Key" + day));
            cookiekey.Expires = now.AddSeconds(-1);
            cookie.HttpOnly = true;
            HttpContext.Current.Response.AppendCookie(cookiekey);

            //清除Cookie
            HttpCookie cookieaccoutkey = new HttpCookie(Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "AccountKey" + day));
            cookie.Expires = now.AddSeconds(-1);
            cookie.HttpOnly = true;
            HttpContext.Current.Response.AppendCookie(cookieaccoutkey);

            //删除Session
            HttpContext.Current.Session.Clear();
        }

        /// <summary>
        /// 登录
        /// </summary>
        public bool LogOn(string openid = "")
        {
            if (string.IsNullOrWhiteSpace(openid))
            {
                return false;
            }
            else
            {
                var t = this.Getwx_users(new wx_users { openid = openid });
                if (t == null)
                {
                    return false;
                }
                var now = DateTime.Now;
                var day = now.ToString("yyMMdd");

                var key_id = Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "ID" + day);
                var key_key = Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "Key" + day);

                HttpCookie cookie = new HttpCookie(key_id);
                cookie.Value = t.id.ToString();
                cookie.Expires = now.AddDays(1);
                cookie.HttpOnly = true;
                HttpContext.Current.Response.AppendCookie(cookie);

                HttpCookie cookiekey = new HttpCookie(key_key);
                cookiekey.Value = Common.EncryptionHelper.MD5Helper.Encryt(Prefix + t.id.ToString());
                cookiekey.Expires = now.AddDays(1);
                cookiekey.HttpOnly = true;
                HttpContext.Current.Response.AppendCookie(cookiekey);

                CreateNewSession();

                HttpContext.Current.Session[key_id] = t.id;
                HttpContext.Current.Session[sessionKey] = t;
                HttpContext.Current.Session.Timeout = 30;

                return true;
            }
        }

        public void CreateNewSession()
        {
            SessionIDManager manager = new SessionIDManager();
            manager.RemoveSessionID(HttpContext.Current);
            var newId = manager.CreateSessionID(HttpContext.Current);
            var isRedirected = true;
            var isAdded = true;
            manager.SaveSessionID(HttpContext.Current, newId, out isRedirected, out isAdded);
        }
    }
}
